function exportTrainingData(data)

% Exports in the current working directory the data that will be used for training
% in a mat file named "training_data.mat".
% This function does almost no error-handling!

Pn = [];
Tn = [];
for i = 1 : size(data, 2);
	[P, T] = prepareTrainingData(data(i).filename, data(i).spindleInterval, ...
								 data(i).notSpindleInterval, data(i).samplingRate);
	Pn = [Pn, P];
	Tn = [Tn, T];
end

Tnnot =~ Tn;
Tn = [Tn; Tnnot];

save('training_data', 'Pn', 'Tn', '-v6');

%===============================================================================

function [Pn, Tn] = prepareTrainingData(filename, spindleInterval, notSpindleInterval, samplingRate)
% Extracts the training data (input and target vectors) for an epoch.

data = load(filename);

% Data rate reduction occurs in this step.
switch(samplingRate)
	case 256
		data = data(1:2:4096);
	case 512
		data = data(1:4:8192);
	otherwise
		error('Sampling rate should be 256 or 512.');
end

% Tn: The 2 x n target vectors, where n is the number of input vectors.

% spindle
Pn = [];
Tn = [];
[Pn, windowsCount] = prepareInputVectors(Pn, data, spindleInterval);
Tn = [Tn, ones(1, int16(windowsCount))];

% not spindle 
[Pn, windowsCount] = prepareInputVectors(Pn, data, notSpindleInterval);
Tn = [Tn, zeros(1, int16(windowsCount))];


%===============================================================================
function [Pn, windowsCount] = prepareInputVectors(Pn, data, interval)

% Load the 64 x 1 input vectors in a 64 x n matrix, 
% where n is the number of vectors, that are used for training.
% The matrix represents a sliding window, that moves over the signal one sample 
% a time.  

% Pn: The spindle input vectors.

Pmax = interval(2) * 128;
Pmin = interval(1) * 128;

windowsCount = calcSlidingWindows(64, Pmin, Pmax);

for i = 0 : (windowsCount - 1)
	Pn = [Pn, data((Pmin + i):((Pmin + 63) + i))];
end

%===============================================================================
